const loki = require('lokijs')
const fs = require('fs')
const request = require('superagent');
const cheerio = require('cheerio');

// 启动log
const log4js = require('log4js');
log4js.configure({
    appenders: {
        cheese: {
            type: 'file',
            filename: './avatarFaile.log'
        }
    },
    categories: {
        default: {
            appenders: ['cheese'],
            level: 'trace'
        }
    }
});
const logger = log4js.getLogger('cheese');


var db = new loki('./SD_DB.db', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    serializationMethod: 'pretty',
    autosaveInterval: 4000
});

// implement the autoloadback referenced in loki constructor
function databaseInitialize() {
    var robots = db.getCollection("robots");
    if (robots === null) {
        robots = db.addCollection("robots");
    }
    // kick off any program logic or start listening to external events
    // weaponAnalysis(robots);
    runProgramLogic2(robots);
}


function createRobotDB(robots) {
    var robotJSON = JSON.parse(fs.readFileSync('./SDdata.json'))
    robots.insert(robotJSON)
}

let machineMap = {}
let madchineArr = []

function runProgramLogic(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    var i = 0
    getPic(i)

    function getPic(i) {
        let num = res[i].ID;
        request.get(`https://www.olgame.tw/sds/images/robot/${num}.gif`)
            .then(res => {
                // let num = robotpicPath.match(/\d+\.gif/)
                // fs.writeFileSync(`./fxImg/${num}`, res.text)
                fs.writeFile(`./GundamAvatar/${num}.gif`, res.body, (err) => {
                    if (err) {
                        console.log(`存储图片失败，编号${num}`)
                    }
                    console.log(`头像存储-${num}成功`)
                    console.log(`${i}条`)
                    getPic(++i)
                })
            }).catch(err => {
                console.log(`头像存储-${num}faile, again` + err);
                // fs.writeFileSync(`./GundamAvatar/errLog.log`, `头像存储-${num}faile`)
                logger.error(`头像存储-${num}faile`)
                if (err.status == 404) {
                    getPic(++i)
                } else {
                    getPic(i)
                }
            })
    }
    // robots.update(res)
    // console.log('更新tags完毕')
    // db.save()
}

function runProgramLogic2(robots) {
    let weaponE_map = {},
        weaponE_arr = [];
    let weaponP_map = {},
        weaponP_arr = []
    let force_map = {},
        force_arr = []
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)

    fs.writeFileSync('./sd_dbexport.json', JSON.stringify(res))

}

function weaponAnalysis(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    let moduleArr = [];
    res.forEach(gundam => {
        moduleArr.push(gundam.ID)
        gundam.weaponTable = gundam.weaponTable || '';
        let $ = cheerio.load(gundam.weaponTable)
        if ($('table')[0]) {
            let special1 = $($($('table')[0]).find('tr')[0]).find('.border2').text().trim() || '';
            let weapon1_1img = $($($('table')[0]).find('tr')[1]).find('img').attr('src').trim() || '';
            let weapon1_1Name = $($($('table')[0]).find('tr')[1]).find('b').text().trim() || '';
            let weapon1_1effact = $($($('table')[0]).find('tr')[1]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon1_1_gunNum = $($($('table')[0]).find('tr')[1]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon1_1_gunNum = weapon1_1_gunNum ? weapon1_1_gunNum[0] : '';
            let weapon1_2img = $($($('table')[0]).find('tr')[3]).find('img').attr('src').trim() || '';
            let weapon1_2Name = $($($('table')[0]).find('tr')[3]).find('b').text().trim() || '';
            let weapon1_2effact = $($($('table')[0]).find('tr')[3]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon1_2_gunNum = $($($('table')[0]).find('tr')[3]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon1_2_gunNum = weapon1_2_gunNum ? weapon1_2_gunNum[0] : '';
            let weapon1_3img = $($($('table')[0]).find('tr')[5]).find('img').attr('src').trim() || '';
            let weapon1_3Name = $($($('table')[0]).find('tr')[5]).find('b').text().trim() || '';
            let weapon1_3effact = $($($('table')[0]).find('tr')[5]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon1_3_gunNum = $($($('table')[0]).find('tr')[5]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon1_3_gunNum = weapon1_3_gunNum ? weapon1_3_gunNum[0] : '';
            let shield1_life = $($($($('table')[0]).find('tr')[7]).find('td')[1]).text().trim().match(/\d+.+/) &&
                $($($($('table')[0]).find('tr')[7]).find('td')[1]).text().trim().match(/\d+.+/)[0] || '';
            let shield1_def = $($($($('table')[0]).find('tr')[7]).find('td')[2]).text().trim().match(/\d+.+/) &&
                $($($($('table')[0]).find('tr')[7]).find('td')[2]).text().trim().match(/\d+.+/)[0] || '';

            gundam.weapon1 = {
                "shield": {
                    life: shield1_life,
                    def: shield1_def
                },
                "arms": [{
                        img: weapon1_1img,
                        name: weapon1_1Name,
                        effact: weapon1_1effact,
                        biuNum: weapon1_1_gunNum
                    },
                    {
                        img: weapon1_2img,
                        name: weapon1_2Name,
                        effact: weapon1_2effact,
                        biuNum: weapon1_2_gunNum
                    },
                    {
                        img: weapon1_3img,
                        name: weapon1_3Name,
                        effact: weapon1_3effact,
                        biuNum: weapon1_3_gunNum
                    }
                ],
                "special": special1
            }

        }
        if ($('table')[1]) {
            let special2 = $($($('table')[1]).find('tr')[0]).find('.border2').text().trim() || '';
            let weapon2_1img = $($($('table')[1]).find('tr')[1]).find('img').attr('src').trim() || '';
            let weapon2_1Name = $($($('table')[1]).find('tr')[1]).find('b').text().trim() || '';
            let weapon2_1effact = $($($('table')[1]).find('tr')[1]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon2_1_gunNum = $($($('table')[1]).find('tr')[1]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon2_1_gunNum = weapon2_1_gunNum ? weapon2_1_gunNum[0] : '';
            let weapon2_2img = $($($('table')[1]).find('tr')[3]).find('img').attr('src').trim() || '';
            let weapon2_2Name = $($($('table')[1]).find('tr')[3]).find('b').text().trim() || '';
            let weapon2_2effact = $($($('table')[1]).find('tr')[3]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon2_2_gunNum = $($($('table')[1]).find('tr')[3]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon2_2_gunNum = weapon2_2_gunNum ? weapon2_2_gunNum[0] : '';
            let weapon2_3img = $($($('table')[1]).find('tr')[5]).find('img').attr('src').trim() || '';
            let weapon2_3Name = $($($('table')[1]).find('tr')[5]).find('b').text().trim() || '';
            let weapon2_3effact = $($($('table')[1]).find('tr')[5]).find('[color="#FF6600"]').text().trim().split(/\s+/) || '';
            let weapon2_3_gunNum = $($($('table')[1]).find('tr')[5]).find('[color="#0000FF"]').text().trim().match(/\*\s{0,3}\d+/) || '';
            weapon2_3_gunNum = weapon2_3_gunNum ? weapon2_3_gunNum[0] : '';
            let shield2_life = $($($($('table')[1]).find('tr')[7]).find('td')[1]).text().trim().match(/\d+.+/) &&
                $($($($('table')[1]).find('tr')[7]).find('td')[1]).text().trim().match(/\d+.+/)[0] || '';
            let shield2_def = $($($($('table')[1]).find('tr')[7]).find('td')[2]).text().trim().match(/\d+.+/) &&
                $($($($('table')[1]).find('tr')[7]).find('td')[2]).text().trim().match(/\d+.+/)[0] || '';

            gundam.weapon2 = {
                "shield": {
                    life: shield2_life,
                    def: shield2_def
                },
                "arms": [{
                        img: weapon2_1img,
                        name: weapon2_1Name,
                        effact: weapon2_1effact,
                        biuNum: weapon2_1_gunNum
                    },
                    {
                        img: weapon2_2img,
                        name: weapon2_2Name,
                        effact: weapon2_2effact,
                        biuNum: weapon2_2_gunNum
                    },
                    {
                        img: weapon2_3img,
                        name: weapon2_3Name,
                        effact: weapon2_3effact,
                        biuNum: weapon2_3_gunNum
                    }
                ],
                "special": special2
            }

        }


    });



    fs.writeFileSync('./gundamID.txt', JSON.stringify(moduleArr))
    console.log('write ok')

    robots.update(res)
    console.log('更新force完毕')
    db.save()
}



function encodeUnicode(str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
        res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
}

// 解码
function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
}





module.exports = db;